import json
import traceback

from django.core.paginator import Paginator
from rest_framework.response import Response
from rest_framework.decorators import APIView
# Create your views here.
from leavemsg import models
from leavemsg.seriallizer import LeaveMsgSeriallizer
from tools.log import logger
from tools.tool import get_json_values, get_ip


class LeaveMsg(APIView):
    """
    留言
    """
    def get(self, request):

        li = []
        resp = {"code": -1, "data": li}
        try:
            body = request.query_params.dict()

            leavemsgs = models.LeaveMsg.objects.filter().order_by("-createtime")
            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)
            paginator = Paginator(leavemsgs, page_size)
            leavemsgs = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = LeaveMsgSeriallizer(leavemsgs, many=True)

            resp = {"code": 1, "data": seriallizer.data, 'page_size': page_size, 'page_num': page_num, 'total': total}

        except Exception:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    def post(self, request):

        li = []
        resp = {"code": -1, "data": li}
        try:
            ip = get_ip(request)
            body = json.loads(request.body)

            content = get_json_values("content", body, 10)
            item = models.LeaveMsg(
                content=content,
                ip=ip
            )
            item.save()

            resp = {"code": 1, "data": [], 'msg': '留言成功！'}

        except Exception:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)
